<?php
//DB connection
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db('livechat') or die('Could not select database.');

//function to generate a random key hash based on IP
function genKey() {
    $ip = $_SERVER['REMOTE_ADDR']; // get the users IP address
    $genID = uniqid(mt_rand(), true); // http://php.net/manual/en/function.uniqid.php
    return sha1($ip . $genID);
}

// this function makes our chat
function makeChat($id = NULL, $user = NULL, $access = NULL) {
    if(!isset($access)){
    $sql = "INSERT INTO chat (idChat, chatName, status) VALUES (NULL, '{$id}', 0);";
    mysql_query($sql); // executes sql
    }

    $sql = "SELECT idChat, chatName FROM chat WHERE chatName = '{$id}'";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_assoc($result)) {
        $idC = $row['idChat'];
    }

    $sql = "INSERT INTO user_has_chat (User_idUser, Chat_idChat) VALUES ('{$user}', '{$idC}');";
    mysql_query($sql); // executes sql

    return $idC;
}

//this function is used by the ajax in jquery to get all the content of a chat
function getContent($num) {
    $query = "SELECT m.Time, m.Text, m.User_idUser, m.Chat_idChat, u.idUser, u.FirstName, u.LastName  FROM user u, messages m WHERE u.idUser = m.User_idUser AND Chat_idChat = {$num}";
    $result = mysql_query($query);

    $numResults = mysql_num_rows($result);
    if (mysql_num_rows($result) == 0) {
        echo "Welcome to the Live Chat!";
        exit;
    }
    while ($row = mysql_fetch_assoc($result)) {
        echo '<span style="font-size:large">' . $row["FirstName"] . ' ' . $row["LastName"] . "</span>";
        echo ' - ' . $row["Text"] . "<br />";
    }
}

//this one is used to add in messages from the jquery.
function insertMessage($user, $chat, $message) {
    $sql = "INSERT INTO messages (idMessages, Time, Text, User_idUser, Chat_idChat) VALUES (NULL, NOW(), '{$message}', '{$user}', '{$chat}');";
    $send = mysql_query($sql); // executes sql
    if (!$send)
        die("Error: " . mysql_error());
    else
        return $send;
}

function getChatList(){
    $query = "SELECT c.idChat, c.chatName, c.status, h.User_idUser, h.Chat_idChat, u.idUser, u.FirstName FROM chat c, user_has_chat h , user u WHERE u.idUser = h.User_idUser AND c.idChat = h.Chat_idChat";
    $result = mysql_query($query) or die(mysql_error());
    while ($row = mysql_fetch_assoc($result)) {
        echo '<option value="'. $row["idChat"].'">' . $row["idChat"] . ' ' . $row["FirstName"] . "</option><br/>";
    }
}